package com.ddwl.user.repository.impl;

import com.ddwl.schema.model.Location;
import com.ddwl.user.model.Track;
import com.ddwl.user.repository.TrackRepositoryAdvance;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.aggregation.Aggregation;
import org.springframework.data.mongodb.core.aggregation.AggregationResults;
import org.springframework.data.mongodb.core.query.Criteria;

import java.util.Collection;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author Fu Zhaohui
 * @version 1.0.0
 * @date 2021/6/16 15:49
 */
public class TrackRepositoryImpl implements TrackRepositoryAdvance {

    @Autowired
    private MongoTemplate template;

    @Override
    public Map<String, Location> findLatestByMacAndUserId(Collection<String> macs, String userId) {
        Criteria criteria = Criteria.where("mac").in(macs).and("userId").is(userId);
        Aggregation aggregation = Aggregation.newAggregation(Aggregation.match(criteria),
                Aggregation.group("mac").last("loc").as("loc"));
        AggregationResults<Map> results = template.aggregate(aggregation, Track.class, Map.class);
        return results.getMappedResults().stream().collect(Collectors.toMap(map -> map.get("_id").toString(), map -> {
            LinkedHashMap<String, Object> loc = (LinkedHashMap) map.get("loc");
            return new Location(Double.valueOf(loc.get("lng").toString()), Double.valueOf(loc.get("lat").toString()));
        }, (k1, k2) -> k1));
    }
}
